<?php

include_once "Item.php";
include_once "Leaf.php";
include_once "petitElf.php";

if (Settings::$showErrors) {
    error_reporting(E_ALL);
}

while (true) {
    if (isset($_GET["lang"])) {
        if ($_GET["lang"] == "cz") {
            include_once 'lang/cze.php';
            setLangVisibility("cz");
            break;
        }
        if ($_GET["lang"] == "ru") {
            include_once 'lang/ru.php';
            setLangVisibility("ru");
            break;
        }
        if ($_GET["lang"] == "en") {
            include_once 'lang/en.php';
            setLangVisibility("en");
            break;
        }
        include_once 'lang/cze.php';
        setLangVisibility("cz");
        break;
    } else {
        if (isset($_COOKIE['lang'])) {
            if ($_COOKIE['lang'] == "cz") {
                include_once 'lang/cze.php';
                setLangVisibility("cz");
                break;
            }
            if ($_COOKIE['lang'] == "ru") {
                include_once 'lang/ru.php';
                setLangVisibility("ru");
                break;
            }
            if ($_COOKIE['lang'] == "en") {
                include_once 'lang/en.php';
                setLangVisibility("en");
                break;
            }
            include_once 'lang/cze.php';
            setLangVisibility("cz");
            break;
        } else {
            include_once 'lang/cze.php';
            setLangVisibility("cz");
            break;
        }
    }
}

$SQL = new SQL();

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of manager_util
 *
 * @author hodek
 */
function loadTemplate($name) {
    return loadTemplateWithPath($name, Settings::$template_path);
}

function loadTemplateWithPath($name, $path) {
    global $loadTemplatePath;
    $loadTemplatePath = $path;
    $fload = $path . $name . '.' . Settings::$template_ext_html;
    if (file_exists($fload)) {
        $fd = fopen($fload, 'r');
        $tpl = fread($fd, filesize($fload));
        fclose($fd);
        return $tpl;
    }else
        die("TEMPLATE NOT FOUND: $fload");
}

function parseTemplate($tpl) {
    return parseTemplateWithPreview($tpl, 0, 0, 0);
}

function parseTemplateWithPreview($tpl, $preview) {
    return parseTemplateAll($tpl, $preview, 0, 0);
}

global $menuDiveNumber;

/**
 * parsovani html
 *
 * @param type $tpl - nacteny template metodou loadTemplate
 * @param type $preview - 0, 1
 * @param type $item - id itemu z itemmap
 * @param type $typeId - neimplementovano zadejte treba 0
 * @return type 
 */
function parseTemplateAll($tpl, $preview, $item, $typeId) {
    $ex = explode('${', $tpl);
    $exs = sizeof($ex);
    for ($i = 1; $i < $exs; $i++) {
        $whole = substr($ex[$i], 0, strpos($ex[$i], "}"));
        $type = explode('_', $whole);
        $name = $type[1];
//template
        if ($type[0] == Settings::$template_parameters_types[0]) {
            $tpl = str_replace('${' . $type[0] . '_' . $name . '}', parseTemplateWithPreview(loadTemplate($name), $preview), $tpl);
            continue;
        }
//text
        if ($type[0] == Settings::$template_parameters_types[1]) {
            if (!$preview) {
                $query = sprintf(SQL::$select_text_byName, mysql_real_escape_string($name));
            } else {
                $query = sprintf(SQL::$select_text_byName_preview, mysql_real_escape_string($name));
            }
            $result = mysql_query($query, $GLOBALS['link']);
            $row = mysql_fetch_assoc($result);
            if (!$row)
                createEmptyText($name);
            $tpl = str_replace('${' . $type[0] . '_' . $name . '}', $row['data'] . adminEditText($name, $preview, $row["data"]), $tpl);
            continue;
        }
//variable
        if ($type[0] == Settings::$template_parameters_types[2]) {
            if (isset($type[2]) && $type[2] == "SPECIAL") {
                $tpl = str_replace('${' . $whole . '}', specialVariable($name), $tpl);             
            } else {
                if (isset($GLOBALS[$name])) {
                    $tpl = str_replace('${' . $type[0] . '_' . $name . '}', $GLOBALS[$name], $tpl);
                } else {
                    $tpl = str_replace('${' . $type[0] . '_' . $name . '}', "", $tpl);
                }
            }
            continue;
        }
//int
        if ($type[0] == Settings::$template_parameters_types[3]) {
            if (!$preview) {
                $query = sprintf(SQL::$select_int_byName, mysql_real_escape_string($name));
            } else {
                $query = sprintf(SQL::$select_int_byName_preview, mysql_real_escape_string($name));
            }
            $result = mysql_query($query, $GLOBALS['link']);
            $row = mysql_fetch_assoc($result);
            if (!$row)
                createEmptyInt($name);
            $tpl = str_replace('${' . $type[0] . '_' . $name . '}', $row['data'] . adminEditInt($name, $preview), $tpl);
            continue;
        }
//date
        if ($type[0] == Settings::$template_parameters_types[4]) {
            if (!$preview) {
                $query = sprintf(SQL::$select_date_byName, mysql_real_escape_string($name));
            } else {
                $query = sprintf(SQL::$select_date_byName_preview, mysql_real_escape_string($name));
            }
            $result = mysql_query($query, $GLOBALS['link']);
            $row = mysql_fetch_assoc($result);
            if (!$row)
                createEmptyDate($name);
            $tpl = str_replace('${' . $type[0] . '_' . $name . '}', $row['data'] . adminEditDate($name, $preview), $tpl);
            continue;
        }
//user
        if ($type[0] == Settings::$template_parameters_types[5]) {
            $tpl = str_replace('${' . $type[0] . '_' . $name . '}', getUser()->getPropertyValue($name), $tpl);
            continue;
        }
//item
        if ($type[0] == Settings::$template_parameters_types[6]) {
            $name = $type[1];
            if ($name == "DELETE") {
                $tpl = str_replace('${' . $whole . '}', adminItemDelete($item, $preview), $tpl);
                continue;
            }
            if ($name == "SECTIONCHANGE") {
                $tpl = str_replace('${' . $whole . '}', adminItemSectionChange($item, $preview), $tpl);
                continue;
            }
            $query = sprintf(SQL::$select_itemBy_idAndName, mysql_real_escape_string($name), mysql_real_escape_string($item));
            $result = mq($query, $GLOBALS["link"]);
            while ($row = mysql_fetch_assoc($result)) {
                if (isset($row["textData"])) {
                    $vyslednyText = $row["textData"];                    
//                    if (isset($type[2])) {
//                        $vyslednyText = substr($vyslednyText, 0, $type[2]);
//                        $vyslednyText .= "..";
//                    }
                    $tpl = str_replace('${' . $whole . '}', $vyslednyText . adminEditText($row["valueId"], $preview, $row["textData"]), $tpl);
                    continue;
                }
                if (isset($row["numberData"])) {
                    $tpl = str_replace('${' . $whole . '}', upravitNumber($row, "numberData", $name) . adminEditInt($row["valueId"], $preview, $row["numberData"]), $tpl);
                    continue;
                }
                if (isset($row["dateData"])) {
                    $tpl = str_replace('${' . $whole . '}', $row["dateData"], $tpl);
                    continue;
                }
                if (isset($type[2]) && isset($row["name"])) {
                    $imageSize = $type[2];
                    if ($imageSize == "EDIT") {
                        $tpl = str_replace('${' . $whole . '}', adminEditImage($row["name"], $preview), $tpl);
                    }
                    if ($imageSize == "FULL") {
                        $tpl = str_replace('${' . $whole . '}', Settings::$templateSys_path . "Image.php?size=full&id=" . $row["name"], $tpl);
                    }
                    if ($imageSize == "MEDIUM") {
                        $tpl = str_replace('${' . $whole . '}', Settings::$templateSys_path . "Image.php?size=medium&id=" . $row["name"], $tpl);
                    }
                    if ($imageSize == "SMALL") {
                        $tpl = str_replace('${' . $whole . '}', Settings::$templateSys_path . "Image.php?size=small&id=" . $row["name"], $tpl);
                    }
                    continue;
                }

                if (isset($row["idcismap"])) {
                    global $editItemId;
                    $editItemId = $item;
                    if (isset($type[2])) {
                        $pridavek = $type[2];
                        if ($pridavek == "ADD") {
                            $tpl = str_replace('${' . $whole . '}', adminNewColour($row["idcismap"], $preview), $tpl);
                        }
                    } else {
                        $tpl = str_replace('${' . $whole . '}', ciselnikContent($row["idcismap"], $preview, $type[1]), $tpl);
                    }
                    continue;
                }
            }
            continue;
        }
//tree
        if ($type[0] == Settings::$template_parameters_types[7]) {
            $typeName = $type[1];
            $templateName = $type[2];
            $query = sprintf(SQL::$select_itemType_byName, mysql_real_escape_string($typeName)
            );
            $result = mysql_query($query, $GLOBALS['link']);
            $row = mysql_fetch_assoc($result);
            if ($row) {
                $mainTagId = $row['id'];
            }
            $GLOBALS['menuDiveNumber'] = 0;
            $GLOBALS['menuCountCategory'] = 0;
            $GLOBALS['loadTemplatePath'] = "";
            $tpl = str_replace('${' . $whole . '}', parseTree($mainTagId, 0, 0, $mainTagId), $tpl);
            continue;
        }
//lang
        if ($type[0] == Settings::$template_parameters_types[8]) {
            $tpl = str_replace('${' . $whole . '}', $GLOBALS["lang"]["$type[1]"], $tpl);
            continue;
        }
//msg
        if ($type[0] == Settings::$template_parameters_types[9]) {
            if (isset($_GET["msg"])) {
                $tpl = str_replace('${' . $whole . '}', $GLOBALS["lang"]["msg"][$_GET["msg"]], $tpl);
            } else {
                $tpl = str_replace('${' . $whole . '}', "", $tpl);
            }
            continue;
        }
    }
    if (isset($GLOBALS['user']) && $preview) {
        $tpl = str_replace('<head>', '<head>  ' . Settings::$sideBarPathJS, $tpl);
        $tpl = str_replace('<body>', '<body>  ' . parseTemplate(loadTemplate("sideBar")), $tpl);
    }
    return $tpl;
}

/**
 * Menu
 * 
 * @param type $mainTagId
 * @return string 
 */
function parseTree($mainTagId, $menuCountCategory, $menuCountCategoryCap, $parent) {
    $newParent = "";
    $query = sprintf(SQL::$select_subtypeMapping_byParent, mysql_real_escape_string($mainTagId)
    );
    $result2 = mq($query, $GLOBALS['link']);
    $newCap = mysql_num_rows($result2);
    $newCount = 0;

    $returnString = '<div class="mainTag">';
    $query = sprintf(SQL::$select_itemType_byId_current, mysql_real_escape_string($mainTagId)
    );
    $result = mq($query, $GLOBALS['link']);
    $arrowSpan = '<span class="arrow bold smallText" style="display: none;"> </span>';    
    if ($result) {
        $row = mysql_fetch_assoc($result);
        if ($row) {
            if ($GLOBALS['menuDiveNumber'] == 1 || $newCap > 0) {
                if ($GLOBALS['menuDiveNumber'] != 1) {
                    if ($menuCountCategory == 1) {
                        $returnString = '<div class="tag horniOdsazeni" style="display: none;">' . $arrowSpan . '<div id="tag_' . $mainTagId . '"><a class="tag menuTop mediumText underline" section="' . $mainTagId . '">';
                    } else {
                        if ($menuCountCategory == $menuCountCategoryCap) {
                            $returnString = '<div class="tag spodniOdsazeni" style="display: none;">' . $arrowSpan . '<div id="tag_' . $mainTagId . '"><a class="tag menuTop mediumText underline" section="' . $mainTagId . '">';
                        } else {
                            $returnString = '<div  class="tag" style="display: none;">' . $arrowSpan . '<div id="tag_' . $mainTagId . '"><a class="tag menuTop mediumText underline" section="' . $mainTagId . '">';
                        }
                    }
                } else {
                    if ($menuCountCategory == 8){
                      $returnString = '<div class="tag" style="padding-top: 25px;">' . $arrowSpan . '<div id="tag_' . $mainTagId . '"><a class="tag menuTop mediumText underline" section="' . $mainTagId . '">';
                    }else{
                        $returnString = '<div class="tag">' . $arrowSpan . '<div id="tag_' . $mainTagId . '"><a class="tag menuTop mediumText underline" section="' . $mainTagId . '">';
                    }                    
                }
                $returnString .= $row['data'];
                $returnString .= '</a>' . adminEditTree($mainTagId, $row["value"], $row["data"], $parent) . ' </div>';
            } else {
                if ($menuCountCategory == 1) {
                    $returnString = '<div  class="tag  horniOdsazeni" style="display: none;">' . $arrowSpan . '<div id="tag_' . $mainTagId . '"><a class="tag smallText underline" section="' . $mainTagId . '">';
                } else {
                    if ($menuCountCategory == $menuCountCategoryCap) {
                        $returnString = '<div class="tag spodniOdsazeni" style="display: none;">' . $arrowSpan . '<div id="tag_' . $mainTagId . '"><a class="tag smallText underline" section="' . $mainTagId . '">';
                    } else {
                        $returnString = '<div class="tag" style="display: none;">' . $arrowSpan . '<div id="tag_' . $mainTagId . '"><a class="tag smallText underline" section="' . $mainTagId . '">';
                    }
                }
                $returnString .= $row['data'];
                $returnString .= '</a>' . adminEditTree($mainTagId, $row["value"], $row["data"], $parent) . "</div>";
            }
            $newParent = $row["value"];
        }
    }

    while ($row2 = mysql_fetch_assoc($result2)) {
        $id = $row2['child'];
        $GLOBALS['menuDiveNumber']++;
        $newCount++;
        $returnString = $returnString . parseTree($id, $newCount, $newCap, $newParent);
    }
    $returnString = $returnString . '</div>';
    $GLOBALS['menuDiveNumber']--;
    return $returnString;
}

function parseTemplatePreview($tpl) {
    return parseTemplateWithPreview($tpl, 1);
}

function adminEditText($name, $preview, $content, $nameType = null) {
    if (getUser() != null && !$preview && getUser()->getRole() == 'admin') {

        global $editTextName;
        global $editTextContent;
        $editTextName = $name;
        $editTextContent = $content;
        if (isset($GLOBALS["loadTemplatePath"])) {
            return parseTemplate(loadTemplateWithPath(Settings::$template_path . "sysTemp/editText", $GLOBALS["loadTemplatePath"]));
        } else {
            return parseTemplate(loadTemplate("sysTemp/editText"));
        }
    }
    return null;
}

function adminEditInt($name, $preview, $content) {
    if (getUser() != null && !$preview && getUser()->getRole() == 'admin') {
        global $editTextName;
        global $editTextContent;
        $editTextName = $name;
        $editTextContent = $content;
        if (isset($GLOBALS["loadTemplatePath"])) {
            return parseTemplate(loadTemplateWithPath(Settings::$template_path . "sysTemp/editInt", $GLOBALS["loadTemplatePath"]));
        } else {
            return parseTemplate(loadTemplate("sysTemp/editInt"));
        }
    }
    return null;
}

function adminEditImage($name, $preview) {
    if (getUser() != null && !$preview && getUser()->getRole() == 'admin') {
        global $editTextName;
        $editTextName = $name;
        if (isset($GLOBALS["loadTemplatePath"])) {
            return parseTemplate(loadTemplateWithPath(Settings::$template_path . "sysTemp/editImage", $GLOBALS["loadTemplatePath"]));
        } else {
            return parseTemplate(loadTemplate("sysTemp/editImage"));
        }
    }
    return null;
}

function adminNewColour($name, $preview) {
    if (getUser() != null && !$preview && getUser()->getRole() == 'admin') {
        global $editTextName;
        $editTextName = $name;
        if (isset($GLOBALS["loadTemplatePath"])) {
            return parseTemplate(loadTemplateWithPath(Settings::$template_path . "sysTemp/newColour", $GLOBALS["loadTemplatePath"]));
        } else {
            return parseTemplate(loadTemplate("sysTemp/newColour"));
        }
    }
    return null;
}

function adminDeleteDynItem($fkname, $preview) {
    if (getUser() != null && !$preview && getUser()->getRole() == 'admin') {
        global $editTextName;
        $editTextName = $fkname;
        if (isset($GLOBALS["loadTemplatePath"])) {
            return parseTemplate(loadTemplateWithPath(Settings::$template_path . "sysTemp/deleteDynImg", $GLOBALS["loadTemplatePath"]));
        } else {
            return parseTemplate(loadTemplate("sysTemp/deleteDynImg"));
        }
    }
    return null;
}

function adminEditDyn($idmap, $idcis, $typ, $preview) {
    if (getUser() != null && !$preview && getUser()->getRole() == 'admin') {
        global $editTextName;
        $editTextName = $idmap;
        global $editDynType;
        $editDynType = $typ;
        global $editDynIdCis;
        $editDynIdCis = $idcis;
        if ($typ == "sklad") {
            if (isset($GLOBALS["loadTemplatePath"])) {
                return parseTemplate(loadTemplateWithPath(Settings::$template_path . "sysTemp/editSklad", $GLOBALS["loadTemplatePath"]));
            } else {
                return parseTemplate(loadTemplate("sysTemp/editSklad"));
            }
        }
        if ($typ == "barvy") {
            if (isset($GLOBALS["loadTemplatePath"])) {
                return parseTemplate(loadTemplateWithPath(Settings::$template_path . "sysTemp/deleteColour", $GLOBALS["loadTemplatePath"]));
            } else {
                return parseTemplate(loadTemplate("sysTemp/deleteColour"));
            }
        }
        if ($typ == "velikosti") {
            if (isset($GLOBALS["loadTemplatePath"])) {
                return parseTemplate(loadTemplateWithPath(Settings::$template_path . "sysTemp/editVelikost", $GLOBALS["loadTemplatePath"]));
            } else {
                return parseTemplate(loadTemplate("sysTemp/editVelikost"));
            }
        }
        if (isset($GLOBALS["loadTemplatePath"])) {
            return parseTemplate(loadTemplateWithPath(Settings::$template_path . "sysTemp/editDyn", $GLOBALS["loadTemplatePath"]));
        } else {
            return parseTemplate(loadTemplate("sysTemp/editDyn"));
        }
    }
    return null;
}

function adminEditDate($name, $preview) {
    if (isset($GLOBALS['user']) && !$preview) {
        return '';
    }
    return null;
}

function adminEditTree($typeId, $typeName, $content, $parent) {
    if (getUser() != null && getUser()->getRole() == 'admin') {
        global $editTextName;
        global $editTextContent;
        global $editTypeName;
        global $editParent;
        $editTextName = $typeId;
        $editTextContent = $content;
        $editTypeName = $typeName;
        $editParent = $parent;
        $return = "";
        if (isset($GLOBALS["loadTemplatePath"])) {
            $return = parseTemplate(loadTemplateWithPath(Settings::$template_path . "sysTemp/editTree", $GLOBALS["loadTemplatePath"]));
            $return .= parseTemplate(loadTemplateWithPath(Settings::$template_path . "sysTemp/editTreeDelete", $GLOBALS["loadTemplatePath"]));
        } else {
            $return = parseTemplate(loadTemplate("sysTemp/editTree"));
            $return .= parseTemplate(loadTemplate("sysTemp/editTreeDelete"));
        }
        return $return;
    }
    return null;
}

function adminItemDelete($itemId, $preview, $nameType = null) {
    if (getUser() != null && !$preview && getUser()->getRole() == 'admin') {

        global $editTextName;
        $editTextName = $itemId;
        if (isset($GLOBALS["loadTemplatePath"])) {
            return parseTemplate(loadTemplateWithPath(Settings::$template_path . "sysTemp/editDelete", $GLOBALS["loadTemplatePath"]));
        } else {
            return parseTemplate(loadTemplate("sysTemp/editDelete"));
        }
    }
}

function adminItemSectionChange($itemId, $preview) {
    if (getUser() != null && !$preview && getUser()->getRole() == 'admin') {
        global $editTextName;
        $editTextName = $itemId;
        if (isset($GLOBALS["loadTemplatePath"])) {
            return parseTemplate(loadTemplateWithPath(Settings::$template_path . "sysTemp/editSection", $GLOBALS["loadTemplatePath"]));
        } else {
            return parseTemplate(loadTemplate("sysTemp/editSection"));
        }
    }
}

function error($msg) {
    
}

function getItemType($stringType) {
    $i = 0;
    foreach (Settings::$type as $value) {
        if ($stringType == $value) {
            return $i;
        }
        $i++;
    }
    return $i;
}

function createEmptyText($name) {
    insertText($name, "FILLME", Settings::$systemAdminId);
}

function createText($name, $data, $editedBy) {
    insertText($name, $data, $editedBy);
}

function createEmptyDate($name) {
    $query = sprintf(SQL::$insert_date_empty, mysql_real_escape_string($name), mysql_real_escape_string(Settings::$systemAdminId)
    );
    $result = mysql_query($query, $GLOBALS['link']);
    $query = sprintf(SQL::$insert_date_preview_empty, mysql_real_escape_string($name), mysql_real_escape_string(Settings::$systemAdminId)
    );
    $result = mysql_query($query, $GLOBALS['link']);
}

function createEmptyInt($name) {
    $query = sprintf(SQL::$insert_int_empty, mysql_real_escape_string($name), mysql_real_escape_string(Settings::$systemAdminId)
    );
    $result = mysql_query($query, $GLOBALS['link']);
    $query = sprintf(SQL::$insert_int_preview_empty, mysql_real_escape_string($name), mysql_real_escape_string(Settings::$systemAdminId)
    );
    $result = mysql_query($query, $GLOBALS['link']);
}

function createInt($name, $data, $editedBy) {
    $query = sprintf(SQL::$insert_int, mysql_real_escape_string($name), mysql_real_escape_string($data), mysql_real_escape_string($editedBy)
    );
    $result = mysql_query($query, $GLOBALS['link']);
    $query = sprintf(SQL::$insert_int_preview, mysql_real_escape_string($name), mysql_real_escape_string($data), mysql_real_escape_string($editedBy)
    );
    $result = mysql_query($query, $GLOBALS['link']);
}

function createEmptyType($name, $value) {
    $query = sprintf(SQL::$insert_itemType_empty, mysql_real_escape_string($name), mysql_real_escape_string($value)
    );
    $result = mysql_query($query, $GLOBALS['link']);
}

function createEmptyItemFull($name, $typeId, $valueId, $valueType, $itemId) {
    $query = sprintf(SQL::$insert_item_empty, mysql_real_escape_string($name), mysql_real_escape_string($typeId), mysql_real_escape_string($valueId), mysql_real_escape_string($valueType), mysql_real_escape_string($itemId)
    );
    $result = mysql_query($query, $GLOBALS['link']);
}

function createEmptyItem($name, $typeId, $valueId, $valueType) {
    createEmptyItemFull($name, $typeId, $valueId, $valueType, 1);
}

function createDyn($name, $editedBy, $cisid) {
    $query = sprintf(SQL::$insert_dyn, mysql_real_escape_string($name), mysql_real_escape_string($editedBy), mysql_real_escape_string($cisid)
    );
    $result = mysql_query($query, $GLOBALS['link']);
    $query = sprintf(SQL::$insert_dyn_preview, mysql_real_escape_string($name), mysql_real_escape_string($editedBy), mysql_real_escape_string($cisid)
    );
    $result = mysql_query($query, $GLOBALS['link']);
}

function getLink() {
    $link = mysql_connect(Settings::$DBhost, Settings::$DBusr, Settings::$DBpwd);
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }
    $db_selected = mysql_select_db(Settings::$DBname, $link);
    if (!$db_selected) {
        die('Can\'t use ' . Settings::$DBname . ' : ' . mysql_error());
    }
    return $link;
}

function hashByMatu($user, $pass) {
    return md5($user . $pass . 'matujetlustouckej');
}

function generateName() {
    return "gen" . generateInt();
}

function generateInt() {
    $query = sprintf(SQL::$insert_genId);
    $result = mysql_query($query, $GLOBALS["link"]);
    return mysql_insert_id();
}

function checkUser() {
    if (getUser() == null) {
        session_start();
        global $user;
        if (isset($_SESSION['SESS_MEMBER_ID'])) {
            $user = $_SESSION['SESS_MEMBER_ID'];
        } else {
            $user = null;
        }
    }
}

function isEmpty($value) {
    if (isset($value)) {
        if (trim($value) == "" || trim($value) == "null") {
            return true;
        } else {
            return false;
        }
    } else {
        return true;
    }
}

function checkUserFinal() {
    checkUser();
    if ($GLOBALS['user'] == null) {
        unset($_SESSION['SESS_MEMBER_ID']);
        header("location: " . Settings::$rootPath . Settings::$manager . "?action=" . Settings::$logOutPage);
        exit();
    }
}

function checkUserAdmin() {
    checkUser();
    if ($GLOBALS['user'] == null) {
        unset($_SESSION['SESS_MEMBER_ID']);
        header("location: " . Settings::$rootPath . Settings::$manager . "?action=" . Settings::$logOutPage);
        exit();
    } else {
        if (getUser()->getRole() != "admin") {
            unset($_SESSION['SESS_MEMBER_ID']);
            header("location: " . Settings::$rootPath . Settings::$manager . "?action=" . Settings::$logOutPage);
            exit();
        }
    }
}

function isAdmin() {
    if (getUser() == null) {
        return false;
    }
    if (getUser()->getRole() == "admin") {
        return true;
    }
    return false;
}

function isRegistered() {
    if (getUser() == null) {
        return false;
    }
    if (getUser()->getEmail() == Settings::$user_neregistrovany) {
        return false;
    } else {
        return true;
    }
}

function saveSession() {
    $_SESSION['SESS_MEMBER_ID'] = $GLOBALS['user'];
    session_write_close();
}

/**
 *
 * @return Admin
 */
function getUser() {
    if (isset($GLOBALS['user'])) {
        return $GLOBALS['user'];
    } else {
        return null;
    }
}

function getValue($valueId, $valueType) {
    if ($valueType == 0) {
        $query = sprintf(SQL::$select_text_byName, mysql_real_escape_string($valueId));
    }
    if ($valueType == 1) {
        $query = sprintf(SQL::$select_int_byName, mysql_real_escape_string($valueId));
    }
    if ($valueType == 2) {
        $query = sprintf(SQL::$select_date_byName, mysql_real_escape_string($valueId));
    }
    $result = mysql_query($query, $GLOBALS["link"]);
    $row = mysql_fetch_assoc($result);
    return $row["data"];
}

function mq($query, $link) {
    $result = mysql_query($query, $link);
    if (Settings::$sqlDebug && ($result == 0)) {
        $query = sprintf(SQL::$insert_sqlDebug, mysql_real_escape_string($query));
        mysql_query($query, $link);
        return false;
    }
    return $result;
}

function q($query) {
    $result = mysql_query($query, $GLOBALS["link"]);
    if (Settings::$sqlDebug && ($result == 0)) {
        $query = sprintf(SQL::$insert_sqlDebug, mysql_real_escape_string($query));
        mysql_query($query, $GLOBALS["link"]);
        exit();
    }
    return $result;
}

function getTypeIdByName($typeName) {
    $query = sprintf(SQL::$select_itemType_byName, mysql_real_escape_string($typeName));
    $result = mq($query, $GLOBALS["link"]);
    $row = mysql_fetch_assoc($result);
    return $row["id"];
}

function getTypeNameById($typeId) {
    $query = sprintf(SQL::$select_itemType_byId_current, $typeId);
    $result = mq($query, $GLOBALS["link"]);
    $row = mysql_fetch_assoc($result);
    return $row["data"];
}

function ciselnikContent($cisId, $preview, $typ) {
    $query = sprintf(SQL::$select_dyncismap_byIdCisMap, mysql_real_escape_string($cisId));
    $result = mq($query, $GLOBALS["link"]);
    $ret = "";
    $retEnd = "";
    $lastIdVal = "";
    $colorImage = "";
    while ($row = mysql_fetch_array($result)) {
        /* barvy */
        if ($row["idcis"] == 1) {
            if ($lastIdVal == $row["fkname"]) {
                continue;
            }
            $lastIdVal = $row["fkname"];
            //$row2 = mysql_fetch_assoc(getRecurrentLinkId($row["fkname"]));
            $ret .= '<div id = "barvaDiv_' . $row["fkname"] . '" class="floatLeft"><img barva="' . $row["fkname"] . '" class="detailBarva pointer hoverAnimationBlack opacityHalf"  src="' . Settings::$templateSys_path . 'Image.php?size=full&id=' . $colorImage . '" width="80" height="30" />' . adminEditDyn($row["fkname"], 0, "barvy", $preview) . '</div>';
        }
        /* velikosti */
        if ($row["idcis"] == 2) {
            $ret .= '<div velikost="' . $row["idval"] . '" class="detailVelikost pointer bold mediumBigText floatLeft opacityHalf">' . $row['value'] . '</div> &nbsp';
            if ($retEnd == "") {
                $retEnd = adminEditDyn($cisId, $row["idcis"], "velikosti", $preview);
            }
        }
        /* sklad */
        if ($row["idcis"] == 3) {
            if (isAdmin()) {
                global $aktualniMnozstvi;
                global $intName;
                $intName = $row["fkname"];
                $text = getIntByName($row["fkname"]);
                $text = $text["data"];
                $aktualniMnozstvi = $text;
                $recBarva = null;
                $recVelikost = null;
                $result2 = getRecurrentLinkId($row["fkname"]);
                while ($row2 = mysql_fetch_assoc($result2)) {
                    if ($recVelikost == null) {
                        $recVelikost = $row2["idlink"];
                    } else {
                        $recBarva = $row2["idlink"];
                    }
                }
                $ret .= '<div id="sklad_' . $recBarva . '_' . $recVelikost . '" class= "hidden" data-type="noinline">' . $GLOBALS["lang"]["kusuNaSklade"] . ":&nbsp;" . $text;
                $ret .= adminEditInt($row["fkname"], $preview, $text);
                $ret .= '</div>';
            } else {
                $ret .= $GLOBALS["lang"]["cenajevcetnedph"];
                break;
            }
        }
        /* image of colour */
        if ($row["idcis"] == 4) {
            $colorImage = $row["fkname"];
        }
    }
    if ($typ == "velikosti" && $ret == "") {
        $ret = adminEditDyn($cisId, 2, "velikosti", $preview);
    }
    return $ret . $retEnd;
}

function updateUserSessionId($userId, $sessionId) {
    $query = sprintf(SQL::$update_userSessionId, mysql_real_escape_string($sessionId), mysql_real_escape_string($userId));
    $result = mq($query, $GLOBALS["link"]);
}

function getDBUserSessionId($userId) {
    $query = sprintf(SQL::$select_userSessionId, mysql_real_escape_string($userId));
    $result = mq($query, $GLOBALS["link"]);
    while ($row = mysql_fetch_array($result)) {
        return $row['sessionId'];
    }
    return null;
}

function login($login, $pass, $redirect = true) {
    $query = sprintf(SQL::$select_user, mysql_real_escape_string($login), mysql_real_escape_string(hashByMatu($login, $pass))
    );

    $result = mq($query, $GLOBALS['link']);
    $loged = false;

    $oldUser = getUser();

    while ($row = mysql_fetch_assoc($result)) {
        checkUser();
        session_regenerate_id();
        $user = new Admin;
        $user->setAdminId($row['id']);
        $user->setRole($row['role']);
        $user->setEmail($row['login']);
        updateUserSessionId($row['id'], session_id());
        if ($redirect) {
            header("location: " . Settings::$rootPath . "" . Settings::$manager . "?action=" . Settings::$afterLoginPage);
        }
        $loged = true;
    }
    //merge
    if ($oldUser != null) {
        $user->setCenaCelk($oldUser->getCenaCelk());
        foreach ($oldUser->getZbozi() as $value) {
            $user->setZbozi($value);
        }
    }
    $_SESSION['SESS_MEMBER_ID'] = $user;
    $GLOBALS["user"] = $user;
    session_write_close();

    if (!$loged) {
        header("location: " . Settings::$rootPath . Settings::$manager . "?action=" . Settings::$registerPage . "&msg=spatneHeslo");
    }
}

function createAnonym() {
    session_regenerate_id();
    global $user;
    $user = new Admin;
    $user->setRole(Settings::$role_user);
    $user->setEmail(Settings::$user_neregistrovany);
}

function updateText($name, $data) {
    $query = sprintf(SQL::$update_text_byName_current, mysql_real_escape_string($data), mysql_real_escape_string(getUser()->getAdminId()), mysql_real_escape_string($name));
    $result = mq($query, $GLOBALS['link']);
}

function updateInt($name, $data) {
    $query = sprintf(SQL::$update_int_byName_current, mysql_real_escape_string($data), mysql_real_escape_string(getUser()->getAdminId()), mysql_real_escape_string($name));
    $result = mq($query, $GLOBALS['link']);
    $query = sprintf(SQL::$insert_intHistory, mysql_real_escape_string($name), mysql_real_escape_string($data), mysql_real_escape_string(getUser()->getAdminId()));
    $result = mq($query, $GLOBALS['link']);
}

function addCiselnikMap($id, $idcis, $idval) {
    $query = sprintf(SQL::$insert_dyncismap, mysql_real_escape_string($id), mysql_real_escape_string($idcis), mysql_real_escape_string($idval));
    $result = mq($query, $GLOBALS["link"]);
}

function getIdValByValue($value) {
    $query = sprintf(SQL::$select_ciselnik_byValue, mysql_real_escape_string($value));
    $result = mq($query, $GLOBALS["link"]);
    while ($row = mysql_fetch_array($result)) {
        return $row["idval"];
    }
    return null;
}

function addCiselnikMapFull($id, $idcis, $idval, $fkname) {
    $query = sprintf(SQL::$insert_dyncismap_full, mysql_real_escape_string($id), mysql_real_escape_string($idcis), mysql_real_escape_string($idval), mysql_real_escape_string($fkname));
    $result = mq($query, $GLOBALS["link"]);
}

function deleteItem($itemId) {
    $query = sprintf(SQL::$delete_itemFromMap_byItemId, mysql_real_escape_string($itemId));
    $result = mq($query, $GLOBALS["link"]);
}

function updateSection($itemId, $newSectionId) {
    $query = sprintf(SQL::$update_section_byItemId, mysql_real_escape_string($newSectionId), mysql_real_escape_string($itemId));
    $result = mq($query, $GLOBALS["link"]);
}

function uploadFile($inputName, $name) {
    if ($name == "newImage" || $name == "insertImage") {
        $name = generateName();
    }

    $maxsize = 1024 * 8 * 1024 * 5;

    if (is_uploaded_file($_FILES[$inputName]['tmp_name'])) {

        if ($_FILES[$inputName]['size'] < $maxsize) {
            $file = $_FILES[$inputName]['tmp_name'];
            $fileName = $_FILES[$inputName]['name'];
            $imgData = imagecreatefromstring(file_get_contents($file));
            list($width, $height) = getimagesize($file);
            ob_start();
            imagejpeg($imgData);
            $full = ob_get_contents();
            ob_end_clean();
            $full = base64_encode($full);

            $image_medium = imagecreatetruecolor(200, 250);
            imagecopyresampled($image_medium, $imgData, 0, 0, 0, 0, 200, 250, $width, $height);

            $image_small = imagecreatetruecolor(47, 47);
            imagecopyresampled($image_small, $imgData, 0, 0, 0, 0, 47, 47, $width, $height);

            $ext = explode(".", $fileName);

            ob_start();
            imagejpeg($image_medium);
            $medium = ob_get_contents();
            ob_end_clean();
            $medium = base64_encode($medium);

            ob_start();
            imagejpeg($image_small);
            $small = ob_get_contents();
            ob_end_clean();
            $small = base64_encode($small);

            $query = sprintf(SQL::$select_img_byName_small, mysql_real_escape_string($name));
            $result = mq($query, $GLOBALS["link"]);
            $row = mysql_fetch_array($result);
            if ($row) {
                $query = sprintf(SQL::$update_img, mysql_real_escape_string(getUser()->getAdminId()), $full, $medium, $small, mysql_real_escape_string($ext[1]), mysql_real_escape_string($name)
                );
                $result = mq($query, $GLOBALS["link"]);
            } else {
                $query = sprintf(SQL::$insert_img, mysql_real_escape_string($name), mysql_real_escape_string(getUser()->getAdminId()), $full, $medium, $small, mysql_real_escape_string($ext[1])
                );
                $result = mq($query, $GLOBALS["link"]);
            }


            /* obrazky jsou bez preview
              $query = sprintf(SQL::$insert_img_preview, $name, mysql_real_escape_string(getUser()->getAdminId()), $full, $medium, $small, $ext[1]
              );
              $result = mq($query, $GLOBALS["link"]);
             * */

            imagedestroy($image_medium);
            imagedestroy($image_small);
            imagedestroy($imgData);
            getUser()->setLastImage($name);
        }
    } else {
        echo
        '<div>File exceeds the Maximum File limit</div>
          <div>Maximum File limit is ' . $maxsize . '</div>
          <div>File ' . $_FILES[$inputName]['name'] . ' is ' . $_FILES[$inputName]['size'] . ' bytes</div>
          <hr />';
    }
}

function changeSectionParent($sectionId, $newParrentId) {
    $query = sprintf(SQL::$update_sectionParent, mysql_real_escape_string($newParrentId), mysql_real_escape_string($sectionId));
    $result = mq($query, $GLOBALS["link"]);
}

function createDefaultImage($newDefaultName) {
    $query = sprintf(SQL::$copyImage, mysql_real_escape_string($newDefaultName), mysql_real_escape_string(Settings::$defaultImage));
    mq($query, $GLOBALS["link"]);
}

function deleteTree($treeId) {
    $query = sprintf(SQL::$delete_tree, mysql_real_escape_string($treeId));
    $result = mq($query, $GLOBALS["link"]);
}

function insertText($name, $data, $editedBy) {
    $query = sprintf(SQL::$insert_textcz, mysql_real_escape_string($name), mysql_real_escape_string($data), mysql_real_escape_string($editedBy));
    $result = mq($query, $GLOBALS['link']);
    $query = sprintf(SQL::$insert_texten, mysql_real_escape_string($name), mysql_real_escape_string($data), mysql_real_escape_string($editedBy));
    $result = mq($query, $GLOBALS['link']);
    $query = sprintf(SQL::$insert_textru, mysql_real_escape_string($name), mysql_real_escape_string($data), mysql_real_escape_string($editedBy));
    $result = mq($query, $GLOBALS['link']);
}

function getBundleAjaxMsg($msg) {
    return $GLOBALS["lang"]["ajax"][$msg];
}

function getBundleMsg($msg) {
    return $GLOBALS["lang"][$msg];
}

function deleteDynItemByFkname($fkname) {
    $query = sprintf(SQL::$delete_dyncismap_byfkname, mysql_real_escape_string($fkname));
    $result = mq($query, $GLOBALS["link"]);
}

function getIntByName($name) {
    $query = sprintf(SQL::$select_int_byName, mysql_real_escape_string($name));
    $result = mq($query, $GLOBALS["link"]);
    return mysql_fetch_assoc($result);
}

function getRecurrentLinkId($mainId) {
    $query = sprintf(SQL::$select_recurrentLinkId, mysql_real_escape_string($mainId));
    $result = mq($query, $GLOBALS["link"]);
    return $result;
}

function getRecurrentMainId($linkId) {
    $query = sprintf(SQL::$select_recurrentLinkId, mysql_real_escape_string($mainId));
    return mq($query, $GLOBALS["link"]);
}

function setLangVisibility($lang) {
    if ($lang == "cz") {
        $GLOBALS["langCZClass"] = "selectedLang";
        $GLOBALS["langENClass"] = "notSelectedLang";
        $GLOBALS["langRUClass"] = "notSelectedLang";
    }
    if ($lang == "en") {
        $GLOBALS["langCZClass"] = "notSelectedLang";
        $GLOBALS["langENClass"] = "selectedLang";
        $GLOBALS["langRUClass"] = "notSelectedLang";
    }
    if ($lang == "ru") {
        $GLOBALS["langCZClass"] = "notSelectedLang";
        $GLOBALS["langENClass"] = "notSelectedLang";
        $GLOBALS["langRUClass"] = "selectedLang";
    }
}

?>
